package com.cyan.app.workflow.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.fragment.BaseFragment;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.common.LoginProxy;
import com.cyan.app.workflow.common.UserConfiger;
import com.cyan.app.workflow.util.AppUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class UserLoginFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = "UserLoginFragment";

    private TextView top_bar_left;
    private TextView top_bar_middle;
    private AutoCompleteTextView user_name;
    private EditText user_pwd;
    private TextView forget_password;
    private TextView config_server;
    private Button login_btn;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        _RootView = inflater.inflate(R.layout.layout_login, null);
        return _RootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private boolean pwdAllDel = false;
    private boolean usrAllDel = true;

    private void initView() {
        top_bar_left = (TextView) _RootView.findViewById(R.id.top_bar_left);
        top_bar_left.setVisibility(View.GONE);
        top_bar_left.setOnClickListener(this);
        top_bar_middle = (TextView) _RootView.findViewById(R.id.top_bar_middle);
        top_bar_middle.setText(R.string.login);
        user_name = (AutoCompleteTextView) _RootView.findViewById(R.id.user_name);
        user_name.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    if (usrAllDel) {
                        user_name.setText("");
                        usrAllDel = false;
                    }
                } else {
                    usrAllDel = false;
                }
                return false;
            }
        });
        user_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    pwdAllDel = true;
            }
        });
        user_pwd = (EditText) _RootView.findViewById(R.id.user_pwd);
        user_pwd.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    if (pwdAllDel) {
                        pwdAllDel = false;
                        user_pwd.setText("");
                    }
                } else {
                    pwdAllDel = false;
                }
                return false;
            }
        });
        user_pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    usrAllDel = true;
            }
        });

        SharedPreferences sp = getActivity().getSharedPreferences("userNamesFile", Activity.MODE_PRIVATE);

        ArrayList<String> allUserName = new ArrayList<String>(sp.getAll().keySet());
        List<String> listUser = new ArrayList<String>();
        for (int i = 0; i < allUserName.size(); ++i) {
            if(allUserName.get(i) != null) {
                if ("".equals(allUserName.get(i)) || allUserName.get(i).startsWith("last-")) {

                } else {
                    listUser.add(allUserName.get(i));
                }
            }
        }

        ArrayAdapter<String> etUserNameAdapter = new ArrayAdapter<String>(getActivity(),
                R.layout.username_dropdown_item, listUser);
        etUserNameAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        user_name.setAdapter(etUserNameAdapter);

        UserConfiger.UserLocalData userData = UserConfiger.read(sp);
        if (LoginProxy.LOGIN_TYPE_USERNAME.equals(userData.userType)) {
            user_name.setText(userData.userName);
            user_pwd.requestFocus();
        }

        forget_password = (TextView) _RootView.findViewById(R.id.forget_password);
        forget_password.setOnClickListener(this);
        config_server = (TextView) _RootView.findViewById(R.id.config_server);
        config_server.setOnClickListener(this);
        login_btn = (Button) _RootView.findViewById(R.id.login_btn);
        login_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forget_password:
                break;
            case R.id.config_server:
                config();
                break;
            case R.id.login_btn:
                login();
                break;
        }
    }

    /**
     * 用户登录
     */
    private void login() {
        //关闭键盘
        Object obj;
        if (getActivity() != null) {
            obj = getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (obj != null) {
                InputMethodManager im = (InputMethodManager) obj;
                im.hideSoftInputFromWindow(user_pwd.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }

        String name = user_name.getText().toString();
        String pwd = user_pwd.getText().toString();
        if (TextUtils.isEmpty(name)) {
            AppUtils.showTip(getActivity(), R.string.username_cannot_be_empty);
        } else if (TextUtils.isEmpty(pwd)) {
            AppUtils.showTip(getActivity(), R.string.password_cannot_be_empty);
        } /*else if (AppUtils.getCharacterNum(name) < 6 || AppUtils.getCharacterNum(name) > 16) {
            AppUtils.showTip(getActivity(), R.string.username_validation_failed);
        } */else {
            JSONObject param = new JSONObject();
            try {
                param.put("Token", "");
                param.put("name", "");
                param.put("Password", pwd);
                param.put("UserNo", name);
                param.put("FacNo", HttpConfig.Main_FacNo);
                param.put("usertype", LoginProxy.LOGIN_TYPE_USERNAME);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            LoginProxy.getInstance(getActivity()).login(param, LoginProxy.EXTRA_DATA_NORMAL);
            user_pwd.setText("");
        }
    }


    ///设置链接
    private void config(){
        final EditText serveripET;
        final EditText facnoET;
        final EditText facidET;
        Button cancelBT;
        Button configBT;
         String serverIP;

         String facno;
        String facid;



            final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();

            alertDialog.show();
            Window window = alertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setWindowAnimations(R.style.AnimBottom);
            window.setContentView(R.layout.activity_config);
            window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            //只用下面这一行弹出对话框时需要点击输入框才能弹出软键盘
            window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            //加上下面这一行弹出对话框时软键盘随之弹出
           // window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

            serveripET = (EditText)window.findViewById(R.id.editText_serverip);
            facnoET = (EditText)window.findViewById(R.id.editText_facno);
            facidET = (EditText)window.findViewById(R.id.editText_facid);
            /*getSystemService()如果在activity里面就可以直接调用,如果在其他的地方要先调用getActivity()*/



            alertDialog.setCancelable(true);
            alertDialog.setCanceledOnTouchOutside(true);
            SharedPreferences mSharedPreferences =  getActivity().getSharedPreferences("cyan_config", Activity.MODE_PRIVATE);
            serverIP = mSharedPreferences.getString("ServerIP","192.168.1.1");

            facno = mSharedPreferences.getString("facno","A");
            facid = mSharedPreferences.getString("facid","E03BD96D-6BF3-1014-6380-001FE1C4AA87");
            cancelBT = (Button) window.findViewById(R.id.btCancel);
            configBT = (Button) window.findViewById(R.id.btConfig);

            serveripET.setText(serverIP);
            facnoET.setText(facno);
            facidET.setText(facid);
            configBT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    SharedPreferences mSharedPreferences = getActivity().getSharedPreferences("cyan_config", Activity.MODE_PRIVATE);
                    mSharedPreferences.edit().putString("ServerIP",serveripET.getText().toString() ).commit();
                    mSharedPreferences.edit().putString("facno",facnoET.getText().toString() ).commit();
                    mSharedPreferences.edit().putString("facid",facidET.getText().toString() ).commit();
                    HttpConfig.HTTP_MAIN_BASE_URL = "http://" + serveripET.getText().toString();
                    HttpConfig.Main_FacNo = facnoET.getText().toString();
                    HttpConfig.Main_FactoryID = facidET.getText().toString();
                    HttpConfig.HTTP_MAIN_SERVER_URL =  HttpConfig.HTTP_MAIN_BASE_URL +"/Services/MainHandler.ashx";
                }
            });
           cancelBT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                }
            });





    }

}